package com.example.demo.gateway;

import com.alibaba.cloud.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import scala.tools.nsc.doc.html.page.JSONObject;

import java.util.List;
import java.util.Objects;

@Component
@RefreshScope
public class GrayscaleGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    EnvProperties envProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders header = response.getHeaders();
        header.add("Content-Type", "application/json; charset=UTF-8");

        List<String> list = request.getHeaders().get("userId");
        if (Objects.isNull(list) || list.isEmpty()) {
            return resultErrorMsg(response," 缺少userId！");
        }
        String userId = list.get(0);
        if (StringUtils.isBlank(userId)) {
            return resultErrorMsg(response," 缺少userId！");
        }
        if (envProperties.getGrayUsers().contains(userId)) {
            //指定灰度版本
            GrayscaleThreadLocalEnvironment.setCurrentEnvironment(envProperties.getGrayVersion());
        } else {
            //指定生产版本
            GrayscaleThreadLocalEnvironment.setCurrentEnvironment(envProperties.getProVersion());
        }
        return chain.filter(exchange.mutate().request(request).build());
    }

    public int getOrder() {
        return -1;
    }

    private Mono<Void> resultErrorMsg(ServerHttpResponse response, String msg) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "403");
        jsonObject.put("message", msg);
        DataBuffer buffer = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Mono.just(buffer));
    }
}
